package library.client.controller;

import library.client.domain.po.User;
import library.client.response.ResponseResult;
import library.client.service.IUsersService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

/**
 * 用户相关接口
 *
 * 
 *
 */
@RestController
@RequestMapping("/users")
@Api(tags = "用户相关接口")
@RequiredArgsConstructor
@Slf4j
public class UsersController {
    private final IUsersService usersService;

    @GetMapping("login/{username}/{password}")
    @ApiOperation("登录")
    public ResponseResult<Long> login(@PathVariable String username,
                                      @PathVariable String password) {
        try {
            return ResponseResult.success(usersService.login(username, password));
        } catch (IllegalArgumentException iae) {
            return ResponseResult.fail(iae.getMessage());
        }
    }
    
    @PostMapping("register")
    @ApiOperation("用户注册")
    public ResponseResult<Long> register(@RequestBody User user) {
        try {
            log.info("开始注册用户: {}", user.getUsername());
            Long userId = usersService.register(user);
            log.info("用户注册成功，ID: {}", userId);
            return ResponseResult.success(userId);
        } catch (IllegalArgumentException iae) {
            log.warn("用户注册参数错误: {}", iae.getMessage());
            return ResponseResult.fail(iae.getMessage());
        } catch (Exception e) {
            log.error("用户注册失败", e);
            return ResponseResult.fail("注册失败，请稍后重试");
        }
    }
}
